import turtle
import random
import time

# 游戏设置
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
PLAYER_SPEED = 10
ENEMY_SPEED = 2
BULLET_SPEED = 15
ENEMY_SPAWN_RATE = 50  # 数值越小生成越快

# 创建屏幕
screen = turtle.Screen()
screen.setup(SCREEN_WIDTH, SCREEN_HEIGHT)
screen.bgcolor("black")
screen.title("星际战机 (Turtle版)")
screen.tracer(0)  # 关闭自动刷新

# 玩家飞船
player = turtle.Turtle()
player.shape("triangle")
player.color("blue")
player.penup()
player.speed(0)
player.setheading(90)  # 朝上
player.goto(0, -SCREEN_HEIGHT//2 + 50)

# 子弹列表
bullets = []

# 敌人列表
enemies = []

# 分数显示
score = 0
score_display = turtle.Turtle()
score_display.speed(0)
score_display.color("white")
score_display.penup()
score_display.hideturtle()
score_display.goto(0, SCREEN_HEIGHT//2 - 40)
score_display.write(f"分数: {score}", align="center", font=("SimHei", 24, "normal"))

# 移动函数
def move_left():
    x = player.xcor()
    x -= PLAYER_SPEED
    if x > -SCREEN_WIDTH//2:
        player.setx(x)

def move_right():
    x = player.xcor()
    x += PLAYER_SPEED
    if x < SCREEN_WIDTH//2:
        player.setx(x)

def move_up():
    y = player.ycor()
    y += PLAYER_SPEED
    if y < SCREEN_HEIGHT//2 - 20:
        player.sety(y)

def move_down():
    y = player.ycor()
    y -= PLAYER_SPEED
    if y > -SCREEN_HEIGHT//2 + 20:
        player.sety(y)

def fire_bullet():
    bullet = turtle.Turtle()
    bullet.shape("square")
    bullet.color("yellow")
    bullet.shapesize(stretch_wid=0.5, stretch_len=0.2)
    bullet.penup()
    bullet.speed(0)
    bullet.setheading(90)
    bullet.goto(player.xcor(), player.ycor() + 20)
    bullets.append(bullet)

# 键盘绑定
screen.listen()
screen.onkeypress(move_left, "Left")
screen.onkeypress(move_right, "Right")
screen.onkeypress(move_up, "Up")
screen.onkeypress(move_down, "Down")
screen.onkeypress(fire_bullet, "space")

# 生成敌人
def create_enemy():
    enemy = turtle.Turtle()
    enemy.shape("triangle")
    enemy.color("red")
    enemy.penup()
    enemy.speed(0)
    enemy.setheading(270)  # 朝下
    x = random.randint(-SCREEN_WIDTH//2 + 20, SCREEN_WIDTH//2 - 20)
    y = SCREEN_HEIGHT//2 - 20
    enemy.goto(x, y)
    enemies.append(enemy)

# 主游戏循环
running = True
frame_count = 0

while running:
    try:
        screen.update()
        
        # 生成敌人
        frame_count += 1
        if frame_count % ENEMY_SPAWN_RATE == 0:
            create_enemy()
        
        # 移动子弹
        for bullet in bullets[:]:
            y = bullet.ycor()
            y += BULLET_SPEED
            bullet.sety(y)
            
            # 移除超出屏幕的子弹
            if y > SCREEN_HEIGHT//2:
                bullet.hideturtle()
                bullets.remove(bullet)
        
        # 移动敌人
        for enemy in enemies[:]:
            y = enemy.ycor()
            y -= ENEMY_SPEED
            enemy.sety(y)
            
            # 移除超出屏幕的敌人
            if y < -SCREEN_HEIGHT//2:
                enemy.hideturtle()
                enemies.remove(enemy)
        
        # 碰撞检测
        # 子弹击中敌人
        for bullet in bullets[:]:
            for enemy in enemies[:]:
                if (bullet.xcor() - 10 < enemy.xcor() < bullet.xcor() + 10 and
                    bullet.ycor() - 10 < enemy.ycor() < bullet.ycor() + 10):
                    bullet.hideturtle()
                    bullets.remove(bullet)
                    enemy.hideturtle()
                    enemies.remove(enemy)
                    score += 10
                    score_display.clear()
                    score_display.write(f"分数: {score}", align="center", font=("SimHei", 24, "normal"))
        
        # 敌人撞击玩家
        for enemy in enemies[:]:
            if (player.xcor() - 20 < enemy.xcor() < player.xcor() + 20 and
                player.ycor() - 20 < enemy.ycor() < player.ycor() + 20):
                enemy.hideturtle()
                enemies.remove(enemy)
                # 游戏结束
                score_display.clear()
                score_display.write(f"游戏结束! 最终分数: {score}", align="center", font=("SimHei", 24, "normal"))
                running = False
        
        time.sleep(0.01)
    
    except turtle.Terminator:
        running = False
    except Exception as e:
        print(f"游戏出错: {e}")
        running = False

# 游戏结束后等待点击关闭
screen.exitonclick()
